package gim_client

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type Api struct{}

var api = new(Api)

func InitChatApi(Router *gin.RouterGroup) {
	chatGroup := Router.Group("chat")
	{
		chatGroup.POST("sendMsg", api.sendMsg)
		chatGroup.POST("joinGroup", api.joinGroup)
	}
}

type Response struct {
	Data interface{} `json:"data"`
	Msg  string      `json:"msg"`
}

type Msg struct {
	MsgType int32  `json:"msgType"` // 消息类型 区分私聊/群聊
	ToId    string `json:"toId"`    // 私聊目标id
	GroupId string `json:"groupId"` // 群组目标id
	Content string `json:"content"` // 消息正文
}

func (a *Api) sendMsg(c *gin.Context) {

	var m Msg
	err := c.ShouldBindJSON(&m)
	if err != nil {
		Logger.Error("序列化Msg err ", err)
		c.JSON(http.StatusBadRequest, Response{Msg: "参数序列化错误"})
	}
	err = convertAndSend(SendChatEvent, m)
	if err != nil {
		Logger.Error("发送消息失败 err ", err)
		c.JSON(http.StatusInternalServerError, Response{Msg: "发送消息失败"})
	} else {
		c.JSON(http.StatusOK, Response{Msg: "消息发送成功"})
	}
}

func (a *Api) joinGroup(c *gin.Context) {
	var m Msg
	err := c.ShouldBindJSON(&m)
	if err != nil {
		Logger.Error("序列化Msg err ", err)
		c.JSON(http.StatusBadRequest, Response{Msg: "参数序列化错误"})
	}
	err = convertAndSend(JoinGroupEvent, m)
	if err != nil {
		Logger.Error("发送消息失败 err ", err)
		c.JSON(http.StatusInternalServerError, Response{Msg: "加入群组失败"})
	} else {
		c.JSON(http.StatusOK, Response{Msg: "加入群组成功"})
	}
}
